iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0

Tab 常使用在有限的空間內要呈現的資料較多,且需要對資料類型進行歸類的情況。

資料的內容有可能是純文字,也有可能是表單或是圖片等等,也就是內容的部分要能靈活的嵌入各種類型的資料 🤔

一樣先想想 tab 可能有哪些狀態?

  1. 未選取
  2. 選取中
  3. disabled 禁止選取

實作

  • 先用 interface 定義類型
<script lang="ts" setup>

export interface tabsProps {
  modelValue: string,
  tabs: {
    id: string
    label: string,
    content?: string,
    disabled?: boolean
  }[]
}

interface tabsEmits {
  (event: 'update:modelValue', index: string): void
}

withDefaults(defineProps<tabsProps>(), {
  tabs: () => []
})

defineEmits<tabsEmits>()

</script>


<template>
  <div class="relative">
    <ul class="tab">
      <li
        v-for="(item, index) in tabs"
        :key="item.id"
        class="tab-title"
        :class="{
          'active': modelValue === item.id,
          'disabled': item.disabled
        }"
        @click="$emit('update:modelValue', item.id)"
      >
        <span>{{ item.label }}</span>
      </li>
    </ul>
    <template v-for="item in tabs" :key="item.id">
      <div v-show="modelValue === item.id" class="py-10 text-[16px] leading-8">
        <slot :name="item.id">
          {{ item.content }}
        </slot>
      </div>
    </template>
  </div>
</template>

<style>
.tab {
  @apply ...
}

.tab .tab-title {
  @apply ...
}

.tab .tab-title.disabled {
  @apply ... pointer-events-not;
}

.tab .tab-title span {
  @apply ...
}

.tab .tab-title.active span {
  @apply ...
}

.tab .tab-title.active span::after {
  @apply ...
}

</style>

在這邊我對內容靈活性進行了以下規劃:

  1. 可以透過傳入 content 插入的純文字內容。
  2. 可以透過傳入與 id 對應的 ,自行嵌入內容 (與 content 同時存在的話,將以 slot 內容為優先。)

仔細看的話會發現 中對 disabled 的 tab 我並沒有對進行設定,但使用者無法點到這個 Tab !!!
這時候可以看看 ~在切版規劃的話就可以使用 **pointer-events,**讓使用者無法點擊到 Tab 就不會觸發事件 :P (但還是要寫 function 以防萬一啦)

  • 完成後的樣子~

    <script lang="ts" setup>
    
    const tabsData01 = reactive({
      modelValue: '01',
      tabs: [
        {
          id: '01',
          label: '01 BASE',
          content: 'Tab 用於在同一個頁面上使用來切換不同的畫面,透過點擊 Tab 切換到與其對應的內容,其他選項則會隱藏 。'
        },
        {
          id: '02',
          label: '02 DISABLED',
          disabled: true
        },
        {
          id: '03',
          label: '03 CAT',
          content: 'http 貓貓狀態碼'
        },
        {
          id: '04',
          label: '04 DOG',
          content: 'http 狗狗狀態碼'
    
        }
      ]
    })
    
    </script>
    


上一篇
元件製作 switch
下一篇
元件製作 tooltip
系列文
蓋一個自己的 Nuxt 3 UI Module16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言